<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-row>
              <el-col :span="6">
                <el-form-item label="订单号" prop="orderNumber">
                  <el-input v-model="queryParams.orderNumber" placeholder="请输入订单号" clearable
                            @keyup.enter="handleQuery"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="服务名称" prop="serviceType">
                  <el-input v-model="queryParams.serviceType" placeholder="请输入服务名称" clearable
                            @keyup.enter="handleQuery"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="联系电话" prop="contactPhone">
                  <el-input v-model="queryParams.contactPhone" placeholder="请输入联系电话" clearable
                            @keyup.enter="handleQuery"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="用户" prop="userName">
                  <el-input v-model="queryParams.userName" placeholder="请输入下单用户姓名" clearable
                            @keyup.enter="handleQuery"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="订单状态" prop="dispatchStatus">
                  <el-select v-model="queryParams.dispatchStatus" placeholder="请选择订单状态" clearable>
                   <el-option :key="1" value="Pending" label="待处理"></el-option>
                    <el-option :key="2" value="Processing" label="待接单"></el-option>
                    <el-option :key="3" value="Confirmed" label="处理中"></el-option>
                    <el-option :key="4" value="Completed" label="申请完成"></el-option>
                    <el-option :key="5" value="Returned" label="已退回"></el-option>
                    <el-option :key="6" value="Finished" label="已完成"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="指派律师" prop="lawFirmName">
                  <el-input v-model="queryParams.lawFirmName" placeholder="请输入指派律师" clearable
                            @keyup.enter="handleQuery"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="支付时间" style="width: 308px">
                  <el-date-picker
                    v-model="dateRange"
                    value-format="YYYY-MM-DD"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['lawyer:spuOrder:add']">新增-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"-->
          <!--                       v-hasPermi="['lawyer:spuOrder:edit']">撤回-->
          <!--            </el-button>-->
          <!--          </el-col>-->
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
                       v-hasPermi="['trade:order:remove']">删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
                       v-hasPermi="['trade:order:export']">导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="spuOrderList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="订单ID" align="center" prop="orderId" v-if="false"/>
        <el-table-column label="订单号" align="center" prop="orderNumber" width="160"/>
        <el-table-column label="订单状态" align="center" prop="dispatchStatus">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.dispatchStatus === 'Finished'">{{ convertDispatchStatus(scope.row.dispatchStatus) }} </el-tag>
            <el-tag type="warning" v-else-if="scope.row.dispatchStatus === 'Returned'">{{ convertDispatchStatus(scope.row.dispatchStatus) }}</el-tag>
            <el-tag type="primary" v-else>{{ convertDispatchStatus(scope.row.dispatchStatus) }} </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="服务名称" align="center" prop="serviceType"/>
        <el-table-column label="联系电话" align="center" prop="contactPhone"/>
        <el-table-column label="用户" align="center" prop="userName"/>
        <el-table-column label="下单时间" align="center" prop="orderTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <!--        <el-table-column label="单价/数量" align="center" prop="amount" />-->
        <el-table-column label="金额(元)" align="center" prop="amount">
          <template #default="scope">
            <span>{{ getYuan(scope.row.amount) }} 元</span>
          </template>
        </el-table-column>
        <el-table-column label="支付时间" align="center" prop="paymentTime" width="180"/>
        <el-table-column label="完成时间" align="center" prop="finishedTime" width="180"/>
        <el-table-column label="备注" align="center" prop="orderRemark"/>
        <el-table-column label="指派律师" align="center" prop="lawFirmName">
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="订单详情" placement="top">
              <el-button link type="primary" icon="InfoFilled" @click="handleInfo(scope.row)" v-hasPermi="['trade:order:query']"></el-button>
            </el-tooltip>
            <el-tooltip v-if=" scope.row.dispatchable === '1' && (scope.row.dispatchStatus === 'Pending' || scope.row.dispatchStatus === 'Returned')" content="指派订单处理律师" placement="top">
              <el-button link type="primary" icon="Notification" @click="handleSelectLawFirm(scope.row)" v-hasPermi="['trade:order:assign']"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.dispatchStatus === 'Processing' || scope.row.dispatchStatus === 'Confirmed'" content="撤回分派订单" placement="top">
              <el-button link type="danger" icon="RefreshLeft" @click="handleRevoke(scope.row)"
                         v-hasPermi="['trade:order:revoke']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                  v-model:limit="queryParams.pageSize" @pagination="getList"/>
    </el-card>
    <!-- 添加或修改订单信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="998px" append-to-body>
      <el-form ref="spuOrderFormRef" :model="form" :rules="rules" label-width="110px">
        <el-tabs>
          <el-tab-pane label="订单信息">
            <el-form-item label="订单编号" prop="orderNumber">
              <el-input v-model="form.orderNumber" readonly/>
            </el-form-item>
            <el-form-item label="用户" prop="userName">
              <el-input v-model="form.userName" readonly/>
            </el-form-item>
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" readonly/>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" readonly/>
            </el-form-item>
            <el-form-item label="下单时间" prop="orderTime">
              <el-input v-model="form.orderTime" readonly/>
            </el-form-item>
            <el-form-item label="订单金额(元)" prop="amount">
              <el-input v-model="amountYuan" readonly/>
            </el-form-item>
            <el-form-item label="支付金额(元)" prop="paymentAmount">
              <el-input v-model="paymentAmountYuan" readonly/>
            </el-form-item>
            <el-form-item label="支付时间" prop="paymentTime">
              <el-input v-model="form.paymentTime" readonly/>
            </el-form-item>
            <el-form-item label="完成时间" prop="finishedTime">
              <el-input v-model="form.finishedTime" readonly/>
            </el-form-item>
            <el-form-item label="备注" prop="orderRemark">
              <el-input v-model="form.orderRemark" type="textarea" :rows="3" readonly/>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="服务信息">
            <el-form-item label="图片" prop="spuImage">
              <image-preview :src="form.spuImage" :width="218" :height="218"/>
            </el-form-item>
            <el-form-item label="服务名称" prop="spuName">
              <el-input v-model="form.spuName" readonly/>
            </el-form-item>
            <el-form-item label="分类名称" prop="categoryName">
              <el-input v-model="form.categoryName" readonly/>
            </el-form-item>
            <el-form-item label="售价(元)" prop="spuPrice">
              <el-input v-model="spuPriceYuan" readonly/>
            </el-form-item>
            <el-form-item label="附件" prop="spuPrice">
              <el-tooltip content="点击下载" placement="right">
                <el-link :href="ossFile.url" type="danger">{{ ossFile.originalName }}</el-link>
              </el-tooltip>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="派单信息">
            <el-form-item label="派单人" prop="dispatchName">
              <el-input v-model="form.dispatchName" readonly/>
            </el-form-item>
            <el-form-item label="派单时间" prop="dispatchTime">
              <el-input v-model="form.dispatchTime" readonly/>
            </el-form-item>
            <el-form-item label="接单人" prop="lawFirmName">
              <el-input v-model="form.lawFirmName" readonly/>
            </el-form-item>
            <el-form-item label="接单时间" prop="handleTime">
              <el-input v-model="form.handleTime" readonly/>
            </el-form-item>
            <el-form-item label="处理状态" prop="dispatchStatus">
              <el-input v-model="dispatchStatusName" readonly/>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <!--选择了律师-->
    <SelectLawFirmDialog ref="selectLawFirmDialogRef" @refresh="getList()" />
  </div>
</template>

<script setup name="Order" lang="ts">
import {
  listSpuOrder,
  getSpuOrder,
  delSpuOrder,
  addSpuOrder,
  updateSpuOrder,
  listAssignOrder,
  revokeOrder
} from '@/api/trade/order';
import {
  SpuOrderVo,
  SpuOrderQuery,
  SpuOrderForm,
  SpuOrderAssignVo,
  SpuOrderAssignQuery,
  SpuOrderAssignForm
} from '@/api/trade/order/types';
import {listByIds} from '@/api/system/oss';
import {OssVO} from '@/api/system/oss/types';
import { RouteLocationNormalized } from 'vue-router';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const SelectLawFirmDialog = defineAsyncComponent(() => import('@/views/trade/order/selectLawFirmDialog.vue'));

const spuOrderList = ref<SpuOrderAssignVo[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const route = useRoute();
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const spuOrderFormRef = ref<ElFormInstance>();
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const dispatchStatusName = ref('');
const selectLawFirmDialogRef = ref();
const router = useRouter();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: SpuOrderAssignForm = {
  id: undefined,
  orderId: undefined,
  trackingNumber: undefined,
  dispatchTime: undefined,
  dispatchUserId: undefined,
  dispatchName: undefined,
  dispatchStatus: undefined,
  wxUserId: undefined,
  lawyerId: undefined,
  lawyerName: undefined,
  lawFirmId: undefined,
  lawFirmName: undefined,
  lawyerAvatar: undefined,
  handleTime: undefined,
  deadline: undefined,
  overtime: undefined,
  returnedTime: undefined,
  returnedDesc: undefined,
  completionTime: undefined,
  active: undefined,
  spuId: undefined,
  spuName: undefined,
  categoryId: undefined,
  categoryName: undefined,
  spuImage: undefined,
  spuPrice: undefined,
  spuCount: undefined,
  spuTotalAmount: undefined,
  spuFile: undefined,
  orderNumber: undefined,
  orderStatus: undefined,
  serviceType: undefined,
  contactPhone: undefined,
  userId: undefined,
  userName: undefined,
  orderTime: undefined,
  amount: undefined,
  paymentAmount: undefined,
  paymentTime: undefined,
  transactionId: undefined,
  review: undefined,
  orderRemark: undefined,
  payed: undefined,
  cancellationTime: undefined,
  closeType: undefined,
  dispatchable: undefined,
  email: undefined,
  processedStatus: undefined,
  processedTime: undefined
};

const data = reactive<PageData<SpuOrderAssignForm, SpuOrderAssignQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    serviceType: undefined,
    orderNumber: undefined,
    dispatchStatus: undefined,
    lawFirmName: undefined,
    contactPhone: undefined,
    userName: undefined,
    orderTime: undefined,
    paymentTime: undefined,
    params: {}
  },
  rules: {}
});

const { queryParams, form, rules} = toRefs(data);

const spuPriceYuan = computed(() => {
  return getYuan(form.value.spuPrice);
});

const amountYuan = computed(() => {
  return getYuan(form.value.amount);
});

const paymentAmountYuan = computed(() => {
  return getYuan(form.value.paymentAmount);
});

const getYuan = (fen: string | number) => {
  return Number(fen) / 100;
};

const convertDispatchStatus = (dispatchStatus: string) => {
  if (dispatchStatus === 'Pending') {
    return '待处理';
  }
  if (dispatchStatus === 'Processing') {
    return '待接单';
  }
  if (dispatchStatus === 'Confirmed') {
    return '处理中';
  }
  if (dispatchStatus === 'Completed') {
    return '申请完成';
  }
  if(dispatchStatus === 'Finished'){
    return '已完成';
  }
  if(dispatchStatus === 'Returned'){
    return '已退回';
  }
  return '未定义状态';
};

const ossFile = reactive<OssVO>({
  originalName: undefined,
  url: undefined
});

/** 查询订单信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAssignOrder(proxy?.addDateRange(queryParams.value, dateRange.value));
  spuOrderList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  spuOrderFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: SpuOrderAssignVo[]) => {
  ids.value = selection.map(item => item.orderId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加订单信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: SpuOrderAssignVo) => {
  reset();
  const _orderId = row?.orderId || ids.value[0];
  const res = await getSpuOrder(_orderId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改订单信息';
};

const handleInfo = async (row?: SpuOrderAssignVo) => {
  reset();
  const _orderId = row?.orderId || ids.value[0];
  const res = await getSpuOrder(_orderId);
  Object.assign(form.value, res.data);
  dispatchStatusName.value = convertDispatchStatus(form.value.dispatchStatus);
  dialog.visible = true;
  dialog.title = '订单信息';
  //获取文件信息
  handleOssFle(res.data.spuFile);
};

const handleOssFle = async (ossId: string | number) => {
  if (ossId) {
    const res = await listByIds(ossId);
    const ossData = res.data;
    if (ossData.length > 0) {
      Object.assign(ossFile, ossData[0]);
    }
  }
};

const handleSelectLawFirm = (row?: SpuOrderAssignVo) => {
  selectLawFirmDialogRef.value.openDialog(row);
};

/** 提交按钮 */
const submitForm = () => {
  spuOrderFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.orderId) {
        await updateSpuOrder(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addSpuOrder(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: SpuOrderAssignVo) => {
  const _orderIds = row?.orderId || ids.value;
  await proxy?.$modal.confirm('是否确认删除当前选中的数据项？').finally(() => loading.value = false);
  await delSpuOrder(_orderIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

const handleRevoke = async (row?: SpuOrderAssignVo) => {
  const _trackingNumber = row?.trackingNumber;
  await proxy?.$modal.confirm(`是否确认撤回“${row?.serviceType}”订单？`).finally(() => loading.value = false);
  await revokeOrder(_trackingNumber);
  proxy?.$modal.msgSuccess('操作成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('lawyer/spuOrder/export', {
    ...queryParams.value
  }, `订单信息_${new Date().getTime()}.xlsx`)
};
onMounted(() => {
  getList();
});
</script>
